﻿using System;
using System.IO;
using System.Net;
using System.Text;
using my_proxy.Utils;
using System.Text.RegularExpressions;
using System.Web;


namespace my_proxy.RequestHandlers
{
    public class AnonymousRequestHandler :OpenRequestHandler
    {

        public AnonymousRequestHandler(Configuration cf, HttpListenerContext context, FileReader fr, object fileLock) : base(cf, context, fr, fileLock) { }

        protected override HttpWebRequest GetRequest()
        {
            string re = this.RemoteUrl;
            int index = this.Context.Request.RawUrl.IndexOf("?");
            if (index != -1)
            {
                string start = this.Context.Request.RawUrl.Substring(0, index);
                string input = HttpUtility.UrlDecode(this.Context.Request.RawUrl.Substring(index));
                input = System.Uri.UnescapeDataString(this.Context.Request.RawUrl.Substring(index));
                string pattern = @"\bbgu\b";
                string replace = "BenGurion";

                Regex emailRegex = new Regex(@"\bbgu\b", RegexOptions.IgnoreCase);
                //find items that matches with our pattern
                MatchCollection emailMatches = emailRegex.Matches(input.ToString());
                foreach (Match emailMatch in emailMatches)
                {
                    Log.Info("Word transformed: " + emailMatch.Value + " -> BenGurion");
                }

                string res = Regex.Replace(input, pattern, replace, RegexOptions.IgnoreCase);


                pattern = @"\bise\b";
                replace = "InformationSystemEngineering";

                emailRegex = new Regex(@"\bise\b", RegexOptions.IgnoreCase);
                //find items that matches with our pattern
                emailMatches = emailRegex.Matches(res.ToString());
                foreach (Match emailMatch in emailMatches)
                {
                    Log.Info("Word transformed: " + emailMatch.Value + " -> InformationSystemEngineering");
                }

                res = Regex.Replace(res, pattern, replace, RegexOptions.IgnoreCase);

                pattern = @"\bse\b";
                replace = "SoftwareEngineering";
                emailRegex = new Regex(@"\bse\b", RegexOptions.IgnoreCase);
                //find items that matches with our pattern
                emailMatches = emailRegex.Matches(res.ToString());
                foreach (Match emailMatch in emailMatches)
                {
                    Log.Info("Word transformed: " + emailMatch.Value + " -> SoftwareEngineering");
                }
                res = Regex.Replace(res, pattern, replace, RegexOptions.IgnoreCase);

                re = start + res;

            }

            HttpWebRequest requestToServer = (HttpWebRequest)WebRequest.Create(re);

            // Set some options
            requestToServer.Method = this.Context.Request.HttpMethod;
            requestToServer.UserAgent = this.Context.Request.UserAgent;
            requestToServer.KeepAlive = requestToServer.KeepAlive;
            requestToServer.Proxy = null;

            requestToServer.UserAgent = "Mozilla/1.0 (compatible; MSIE 1.00; Windows 3.11)";
            requestToServer.Headers.Add("Anonymized", "true");


            // For POST, write the post data extracted from the incoming request
            if (requestToServer.Method == "POST")
            {
                const int bufferSize = 1024;
                Stream clientStream = this.Context.Request.InputStream;
                byte[] clientPostData = new byte[bufferSize];
                requestToServer.ContentType = this.Context.Request.ContentType;
                int read = clientStream.Read(clientPostData, 0, bufferSize);
                StringBuilder data = new StringBuilder();
                Stream stream = requestToServer.GetRequestStream();
                //read data untile the end of the stream and write it to the rquest sended
                while (read > 0)
                {

                    string tempString = Encoding.UTF8.GetString(clientPostData, 0, clientPostData.Length);
                    tempString = System.Uri.UnescapeDataString(tempString);
                    /*****************************************************************/

                    string pattern = @"\bbgu\b";
                    string replace = "BenGurion";
                    string res = Regex.Replace(tempString, pattern, replace, RegexOptions.IgnoreCase);
                    Regex emailRegex = new Regex(@"\bbgu\b", RegexOptions.IgnoreCase);
                    //find items that matches with our pattern
                    MatchCollection emailMatches = emailRegex.Matches(tempString.ToString());
                    foreach (Match emailMatch in emailMatches)
                    {
                        Log.Info("Word transformed: " + emailMatch.Value + " -> BenGurion");
                    }

                    pattern = @"\bise\b";
                    replace = "InformationSystemEngineering";

                    emailRegex = new Regex(@"\bise\b", RegexOptions.IgnoreCase);
                    //find items that matches with our pattern
                    emailMatches = emailRegex.Matches(res.ToString());
                    foreach (Match emailMatch in emailMatches)
                    {
                        Log.Info("Word transformed: " + emailMatch.Value + " -> InformationSystemEngineering");
                    }


                    res = Regex.Replace(res, pattern, replace, RegexOptions.IgnoreCase);




                    pattern = @"\bse\b";
                    replace = "SoftwareEngineering";


                    emailRegex = new Regex(@"\bse\b", RegexOptions.IgnoreCase);
                    //find items that matches with our pattern
                    emailMatches = emailRegex.Matches(res.ToString());
                    foreach (Match emailMatch in emailMatches)
                    {
                        Log.Info("Word transformed: " + emailMatch.Value + " -> SoftwareEngineering");
                    }
                    res = Regex.Replace(res, pattern, replace, RegexOptions.IgnoreCase);

                    byte[] buffer = new byte[res.Length * (sizeof(char))];
                    buffer = Encoding.UTF8.GetBytes(res);
                    data.Append(res);
                    /*****************************************************************/
                    stream.Write(buffer, 0, buffer.Length);
                    read = clientStream.Read(clientPostData, 0, bufferSize);

                }
                stream.Close();



                //TODO: check for mails in the request (use data)
                string data1 = System.Uri.UnescapeDataString(data.ToString());
                //string data1 = data.ToString();
                if (Regex.IsMatch(data1, @"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"))
                {
                    Regex emailRegex = new Regex(@"\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*", RegexOptions.IgnoreCase);
                    //find items that matches with our pattern
                    MatchCollection emailMatches = emailRegex.Matches(data1.ToString());
                    foreach (Match emailMatch in emailMatches)
                    {
                        Log.Info("Email blocked: " + emailMatch.Value);
                    }
                    return null;
                }

            }

            //check for mails in the request headers

            for (int i = 0; i < this.Context.Request.Headers.Count; i++)
            {
                if (Regex.IsMatch(System.Uri.UnescapeDataString(this.Context.Request.Headers[i]), @"\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"))
                {
                    Regex emailRegex = new Regex(@"\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*", RegexOptions.IgnoreCase);
                    //find items that matches with our pattern
                    MatchCollection emailMatches = emailRegex.Matches(System.Uri.UnescapeDataString(this.Context.Request.Headers[i]));
                    foreach (Match emailMatch in emailMatches)
                    {
                        Log.Info("Email blocked: " + emailMatch.Value);
                    }
                    return null;
                }

            }

            for (int j = 0; j < requestToServer.Headers.Count; j++)
            {
                string first = requestToServer.Headers.GetKey(j);
                string input = HttpUtility.UrlDecode(requestToServer.Headers[j].ToString());
                input = System.Uri.UnescapeDataString(input);
                string pattern = @"\bbgu\b";
                string replace = "BenGurion";

                Regex emailRegex = new Regex(@"\bbgu\b", RegexOptions.IgnoreCase);
                //find items that matches with our pattern
                MatchCollection emailMatches = emailRegex.Matches(input.ToString());
                foreach (Match emailMatch in emailMatches)
                {
                    Log.Info("Word transformed: " + emailMatch.Value + " -> BenGurion");
                }

                string res = Regex.Replace(input, pattern, replace, RegexOptions.IgnoreCase);


                pattern = @"\bise\b";
                replace = "InformationSystemEngineering";

                emailRegex = new Regex(@"\bise\b", RegexOptions.IgnoreCase);
                //find items that matches with our pattern
                emailMatches = emailRegex.Matches(res.ToString());
                foreach (Match emailMatch in emailMatches)
                {
                    Log.Info("Word transformed: " + emailMatch.Value + " -> InformationSystemEngineering");
                }

                res = Regex.Replace(res, pattern, replace, RegexOptions.IgnoreCase);

                pattern = @"\bse\b";
                replace = "SoftwareEngineering";
                emailRegex = new Regex(@"\bse\b", RegexOptions.IgnoreCase);
                //find items that matches with our pattern
                emailMatches = emailRegex.Matches(res.ToString());
                foreach (Match emailMatch in emailMatches)
                {
                    Log.Info("Word transformed: " + emailMatch.Value + " -> SoftwareEngineering");
                }
                res = Regex.Replace(res, pattern, replace, RegexOptions.IgnoreCase);

                if (!res.Equals(requestToServer.Headers[j].ToString()))
                {
                    requestToServer.Headers.Remove(first);
                    requestToServer.Headers.Add(first, res);

                }



            }

            return requestToServer;
        }




    }
}
